import "babel-polyfill";
import Fraction from "../number/fraction";
import PolynomialTemplate from "./polynomial";

const {zero, one, eq, abs, negate, add, subtract, multiply, square, divide, inverse} = Fraction;

var FractionType = r => Fraction.from(r);
Object.assign(FractionType, {
    zero,
    one,
    isZero: r => r.numerator.sign === 0,
    isOne: r => eq(r, one),
    eq,
    negate,
    add,
    subtract,
    multiply,
    square,
    divide,
    inverse
});

var PolynomialQ = class extends PolynomialTemplate(FractionType) {
    toString(symbol = "x") {
        var data = this._coeff;
        if (data.length === 0) {
            return "0";
        }
        var list = [];
        if (data[0].sign) {
            list.push(`${data[0]}`);
        }
        for (let degree = 1, length = data.length; degree < length; ++degree) {
            let coeff = data[degree];
            if (coeff.sign) {
                if (eq(abs(coeff), one)) {
                    if (list.length === 0) {
                        if (coeff.sign < 0) {
                            list.push("-");
                        }
                    } else {
                        list.push(coeff.sign > 0 ? " + " : " - ");
                    }
                } else {
                    if (list.length === 0) {
                        list.push(`${coeff}*`);
                    } else {
                        list.push(coeff.sign > 0 ? " + " : " - ", `${abs(coeff)}*`);
                    }
                }
                list.push(degree === 1 ? symbol : `${symbol}^${degree}`);
            }
        }
        return list.join("");
    }
};

PolynomialQ.zero = new PolynomialQ();
PolynomialQ.one = new PolynomialQ(1);
PolynomialQ.instance = new PolynomialQ();

export default PolynomialQ;
